<template>
  <page-meta :page-style="`overflow:${drawerVisible ? 'hidden' : 'visible'};`"></page-meta>
  <PageContainer>
    <view class="container">
      <Header
        title="供需管理"
        v-model="headerHeight"
        :z-index="headerZindex"
        :is-box-shadow="false"
      />
      <view class="p-16 bg-white">
        <StatisticsCard :datas="statisticsDatas" title="本会供需数据总览" item-width="303rpx" />
      </view>
      <NavBox :nav-box-data="navBoxData"></NavBox>
      <view class="tabs-box" :style="{ top: headerHeight + 'px' }">
        <view class="tab">
          <Tabs v-model="currentTab" background-color="#FFF" :isScrollTop="false">
            <TabNav tabBarColor="#2878FF" />
            <template v-if="tabsData?.length">
              <TabsItem
                v-for="(item, index) in tabsData"
                @click="handleTabClick"
                :key="index"
                :name="item.title"
                :value="item.id"
              >
                <template>
                  <view class="py-6 px-16">
                    <view class="flex-1" style="height: 72rpx">
                      <TSearch
                        :placeholder="currentTab ? '搜索姓名/单位/供需标题' : '搜索供需'"
                        @confirm="searchConfirm"
                      ></TSearch>
                    </view>
                    <FilterControl
                      @change="filterSubmit"
                      :showSource="!!currentTab"
                      :show-bo-status="!currentTab"
                    ></FilterControl>
                  </view>
                </template>
              </TabsItem>
            </template>
          </Tabs>
        </view>
      </view>
      <ManageList
        v-if="currentTab === 0"
        :parame="manageParame"
        ref="manageListRef"
        @set="handleSet"
        @share="handleShare"
      ></ManageList>
      <LibList v-else :parame="libParame" ref="libListRef" @share="handleShare"></LibList>
      <BusinessOpportunitieSet
        ref="setRef"
        @ok="manageListRef?.refresh()"
        @drawer-visible="(val) => (drawerVisible = val)"
      ></BusinessOpportunitieSet>
      <TButtonGroup :styles="{ backgroundColor: '#fff' }">
        <TButton
          class="gutter-btn"
          text="邀请发布供需"
          type="none"
          custom-class="borderBtn"
          @click="handleInviteMembersPublish"
        />
        <TButton class="gutter-btn" text="代会员发布供需" type="primary" @click="handleToRelease" />
      </TButtonGroup>
    </view>
  </PageContainer>

  <CustomShare v-model:visible="showSharePopup" :z-index="999" @register="customShareRegister" />
</template>

<script lang="ts" setup>
  /* businessOpportunitiesManage 供需管理 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import StatisticsCard from '../components/StatisticsCard/index.vue';
  import { reactive, ref } from 'vue';
  import type { IDataItem } from '../components/StatisticsCard/DataItem.vue';
  import NavBox, { type INavBox } from '../components/NavBox.vue';
  import Tabs from '@/components/tabs/index.vue';
  import TabsItem from '@/components/tabs/item.vue';
  import TabNav from '@/components/tabs/nav.vue';
  import TSearch from '@/components/TSearch/index.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { navigateTo } from '@/router';
  import BusinessOpportunitieSet from './components/BusinessOpportunitieSet/index.vue';
  import { BoStatusEnum, ReleaseTypeEnum } from '@/enums/businessOpportunitiesEnum';
  import type {
    IBoLibListQuery,
    IBusinessOpportunityList,
    ISysBoInfoListQuery,
  } from '@/api/businessOpportunities/type';
  import ManageList from './components/ManageList.vue';
  import LibList from './components/LibList.vue';
  import FilterControl from './components/FilterControl.vue';
  import type { AssTypeEnum } from '@/enums/orderEnum';
  import CustomShare from '@/components/CustomShare/index.vue';
  import { createShareQuery, useAppShare } from '@/hooks/core/useAppShare';
  import { useCustomShare } from '@/components/CustomShare/hooks/useCustomShare';
  import { onPageScroll, onShareAppMessage, onShow, onUnload } from '@dcloudio/uni-app';
  import { getSupplyDemandPosterData, getSupplyDemandWxShareData } from '../components/utils';
  import { addAppShareLog, boUserPromotionCountDataAdd } from '@/api';
  import { createMiniCode } from '@/utils/dynamicConfig';
  import { getBoAuditStatistics, getBoCountInfoByTenant } from '@/api/businessOpportunities';
  import type { CustomNavigateToOptions } from '@/router/types/nav';
  import { BusinessFunctionTypeEnum } from '@/enums/publicModuleEnum';

  const drawerVisible = ref(false);

  const statisticsDatas = reactive<IDataItem[]>([
    {
      name: '供需总数',
      num: 0,
      unit: '个',
    },
    {
      name: '浏览次数',
      num: 0,
      unit: '次',
    },

    {
      name: '累计意向',
      num: 0,
      unit: '个',
    },

    {
      name: '已联系',
      num: 0,
      unit: '次',
    },
  ]);

  const navBoxData = reactive<INavBox[]>([
    {
      text: '发布审核',
      icon: '\ue6d9',

      num: 0,
      fn: () => {
        navigateTo({
          name: 'businessOpportunitieAuditManage',
        });
      },
      bgColor: '#FEF5ED',
      iconColor: '#F77536',
    },

    {
      text: '申请跨会记录',
      icon: '\ue6d6',
      fn: () => {
        navigateTo({
          name: 'crossClubRecords',
        });
      },
      bgColor: '#EFF2FE',
      iconColor: '#4E80F6',
    },
    {
      text: '合作撮合',
      icon: '\ue6d7',
      num: 0,
      fn: () => {
        navigateTo({
          name: 'cooperativeAudit',
        });
      },
      bgColor: '#FFF0ED',
      iconColor: '#F77536',
    },
    {
      text: '推广记录',
      icon: '\ue6c5',
      fn: () => {
        navigateTo({
          name: 'extensionCenter',
        });
      },
      bgColor: '#EFFBF5',
      iconColor: '#28B082',
    },
  ]);
  const queryBoAuditStatistics = async () => {
    const res = await getBoAuditStatistics();
    navBoxData[0].num = res.publisherWaitAuditNum || 0;
    navBoxData[2].num = res.bringTogetherWaitAuditNum || 0;
  };

  const headerHeight = ref(0);
  const headerZindex = ref(999);

  const currentTab = ref(0);
  const tabsData = ref<
    {
      title: string;
      id: number;
    }[]
  >([
    {
      title: '我管理的',
      id: 0,
    },
    {
      title: '供需库',
      id: 1,
    },
  ]);

  const manageParame = reactive<ISysBoInfoListQuery>({
    cooperationTypeIdList: [],
    industryCategoryIdList: [],
    keyWord: '',
    current: 1,
    size: 10,
    boStatus: undefined,
  });

  const libParame = reactive<IBoLibListQuery>({
    cooperationTypeIdList: [],
    industryCategoryIdList: [],
    keyWord: '',
    current: 1,
    size: 10,
    assType: void 0,
  });

  const manageListRef = ref<InstanceType<typeof ManageList>>();
  const libListRef = ref<InstanceType<typeof LibList>>();
  const handleTabClick = () => {};

  function filterSubmit(params: {
    cooperationType: number[];
    industryIds: string[];
    source: AssTypeEnum;
    boStatus: BoStatusEnum | undefined;
  }) {
    if (currentTab.value === 0) {
      // manageParame.assType = params.source;
      manageParame.cooperationTypeIdList = params.cooperationType;
      manageParame.industryCategoryIdList = params.industryIds;
      manageParame.boStatus = params.boStatus;
    } else {
      libParame.assType = params.source;
      libParame.industryCategoryIdList = params.industryIds;
      libParame.cooperationTypeIdList = params.cooperationType;
    }
  }

  const searchConfirm = (keyWord: string) => {
    if (currentTab.value === 0) {
      manageParame.keyWord = keyWord;
      manageParame.current = 1;
      manageParame.size = 10;
      manageListRef.value?.refresh();
    } else {
      libParame.keyWord = keyWord;
      libParame.current = 1;
      libParame.size = 10;
      libListRef.value?.refresh();
    }
  };

  const setRef = ref<InstanceType<typeof BusinessOpportunitieSet>>();
  const handleSet = (v: IBusinessOpportunityList) => {
    setRef.value?.open(v.id);
  };
  const handleToRelease = () => {
    navigateTo({
      name: 'releaseBusinessOpportunities',
      options: {
        releaseType: ReleaseTypeEnum.insteadMember,
        success: () => {
          manageListRef.value?.refresh();
          libListRef.value?.refresh();
        },
      },
    });
  };

  const queryBoCountInfoByTenant = async () => {
    const res = await getBoCountInfoByTenant();
    statisticsDatas[0].num = res.boSum;
    statisticsDatas[1].num = res.browseSum;
    statisticsDatas[2].num = res.cooperationSum;
    statisticsDatas[3].num = res.cooperationSuccessSum;
  };

  const showSharePopup = ref(false);
  const [
    customShareRegister,
    { setWxShareOptions, setShareLogId, setPosterDrawData, setInternalLinkOptions, setButtons },
  ] = useCustomShare({
    buttons: {
      share: true,
      poster: true,
      copyLink: true,
      insertOffiaccount: true,
    },
    disableds: {
      shortLink: true,
    },
  });

  const { setWxSharePath } = useAppShare();
  async function handleShare(item: IBusinessOpportunityList) {
    setButtons({
      share: true,
      poster: true,
      copyLink: true,
      insertOffiaccount: true,
      downloadMiniprogramCode: false,
    });
    uni.showLoading({ title: '分享参数准备中...', mask: true });
    boUserPromotionCountDataAdd({ type: BusinessFunctionTypeEnum.BO, dataId: item.id });

    const query = { id: item.id };
    const path = setWxSharePath({
      name: 'supplyDemandDetails',
      options: query,
    });
    setInternalLinkOptions({
      name: 'supplyDemandDetails',
      options: query,
    });

    const routeQuery = createShareQuery(query);
    const { id: shareLogId } = await addAppShareLog({
      path: 'supplyDemandDetails',
      query: JSON.stringify(routeQuery),
    });

    const codeImg = await createMiniCode({ shareLogId });
    await setWxShareOptions([getSupplyDemandWxShareData(item, path)]);
    const posterData = getSupplyDemandPosterData(item, codeImg!);
    await setPosterDrawData([posterData]);

    setShareLogId(shareLogId);
    showSharePopup.value = true;
    uni.hideLoading();
  }

  /** 邀请创建的分享参数 =========================================== start */
  const query: CustomNavigateToOptions<'boPromotionalPage'>['options'] = {
    type: 'Invitation',
  };
  const routeQuery = createShareQuery(query);
  async function handleInviteMembersPublish() {
    setButtons({
      share: true,
      poster: false,
      copyLink: true,
      insertOffiaccount: true,
      downloadMiniprogramCode: true,
    });
    uni.showLoading({ title: '分享参数准备中...', mask: true });
    const { id: shareLogId } = await addAppShareLog({
      path: 'boPromotionalPage',
      query: JSON.stringify(routeQuery),
    });
    // const codeImg = await createMiniCode({ shareLogId });
    const path = setWxSharePath({
      name: 'boPromotionalPage',
      options: query,
    });
    setInternalLinkOptions({
      name: 'boPromotionalPage',
      options: query,
    });

    setShareLogId(shareLogId);
    await setWxShareOptions([
      {
        path: path,
        imageUrl:
          'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/inviteMembersPublish.png',
        title: '亲爱的朋友，诚邀您来发供需，轻松链接海量资源，开启商业新旅途！',
      },
    ]);
    // await setPosterDrawData([]);
    showSharePopup.value = true;
    uni.hideLoading();
  }

  /** 邀请创建的分享参数 =========================================== end */

  onShareAppMessage((e) => ({}));

  wx.hideShareMenu({
    menus: ['shareAppMessage', 'shareTimeline'],
  });

  onPageScroll(() => {});

  onShow(() => {
    queryBoCountInfoByTenant();
    queryBoAuditStatistics();
  });
</script>

<style lang="scss" scoped>
  .container {
    .tabs-box {
      margin-top: 24rpx;
      position: sticky;
      background-color: #ffffff;
      z-index: 999;
    }
  }
</style>
